import { useSet } from "ahooks";
import useAppStore from "@/store";
import { View } from "@tarojs/components";

import ByIcon from "@/components/ui/ByIcon";
import BySpace from "@/components/ui/BySpace";
import ByButton from "@/components/ui/ByButton";
import ByPopupBottom from "@/components/ui/ByPopupBottom";

import useList from "@/hooks/useList";
import ApiWork from "@/api/work";

import { WorkflowPost } from "@/types/global";


type ItemProps = {
  post: WorkflowPost;
  selected?: boolean;
  onSelected: (nextSelected: boolean) => void;
};

const Item = ({ selected, post, onSelected }: ItemProps) => {
  return (
    <View
      className={`flex-center relative w-[150px] h-[150px] rounded-lg bg-[#f1f1f1]`}
      onClick={() => onSelected(!selected)}
    >
      <text className="text-sm">{post.postName}</text>

      {selected && (
        <View className="absolute top-0 right-0 -translate-y-1/4 translate-x-1/4">
          <ByIcon name="CheckFill" color="var(--color-primary)" size={36} />
        </View>
      )}
    </View>
  );
};

type ByPopupBottomProps = {
  title?: string;
  tip?: string;
  ids?: string;
};

type ByPopupBottomEvent = {
  onCancel?: () => void;
  onConfirm: (ids: string, names: string) => void;
};

export default ({
  ids,
  tip,
  title,

  onCancel,
  onConfirm,
}: ByPopupBottomProps & ByPopupBottomEvent) => {
  const postList = useAppStore((state) => state.postList);

  const upldatePostList = useAppStore((state) => state.updatePostList);

  useList<WorkflowPost[]>(ApiWork.getPostList, {
    manual: !!postList,
    onSuccess(res) {
      upldatePostList(res.list);
    },
  });

  const [selected, { add, remove }] = useSet<number>(ids ? ids.split(",").map(Number) : []);
  const handleConfirm = () => {
    const names = postList!.reduce((list, item) => {
      if (selected.has(item.workflowPostId)) {
        list.push(item.postName);
      }
      return list;
    }, [] as string[]);

    onConfirm([...selected].join(","), names.join(","));
  };

  return (
    <ByPopupBottom
      tip={tip}
      title={title}
      onCancel={onCancel}
      slotFooter={
        <View className="text-center py-4">
          <ByButton
            className="w-1/2"
            size="large"
            disabled={postList?.length == 0}
            onClick={handleConfirm}
          >
            确定
          </ByButton>
        </View>
      }
    >
      <View className="py-2 px-4 h-[60vh] overflow-y-auto">
        <BySpace>
          {postList?.map((item) => (
            <Item
              key={item.workflowPostId}
              post={item}
              selected={selected.has(item.workflowPostId)}
              onSelected={(flag) =>
                flag
                  ? add(item.workflowPostId)
                  : remove(item.workflowPostId)
              }
            />
          ))}
        </BySpace>
      </View>
    </ByPopupBottom>
  );
};
